package com.wmh.baseservice.skd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.service.TokenService;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.skd.pojo.SkdPickupPoint;
import com.wmh.baseservice.skd.pojo.SkdPickupPointCategory;
import com.wmh.baseservice.skd.pojo.vo.AddPickupPointReqVO;
import com.wmh.baseservice.skd.pojo.vo.PickupPointResqVO;
import com.wmh.baseservice.skd.pojo.vo.ModifyPickupPointReqVO;
import com.wmh.baseservice.skd.service.SkdPickupPointCategoryService;
import com.wmh.baseservice.skd.service.SkdPickupPointService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(tags = "自提点管理接口")
@Validated
@RestController
@RequestMapping(value = "pickup-points", produces = "text/plain;charset=utf-8")
@Slf4j
public class PickupPointController {
    @Resource
    private TokenService tokenService;
    @Resource
    private SkdPickupPointService skdPickupPointService;
    @Resource
    private SkdPickupPointCategoryService skdPickupPointCategoryService;

    /**
     * #0023 添加自提点分类
     * @param name 自提点名称
     * @return 返回是否添加成功
     */
    @ApiOperation("添加自提点分类")
    @PostMapping("categories")
    public String addPickupPointCategory(@NotBlank(message = "未提交分类名称") String name) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        SkdPickupPointCategory pickupPointCategory = new SkdPickupPointCategory();
        pickupPointCategory.setName(name);
        pickupPointCategory.setUsId(usId);
        SkdPickupPointCategory res = skdPickupPointCategoryService.getOne(new QueryWrapper<>(pickupPointCategory));
        if (Objects.isNull(res)) {
            skdPickupPointCategoryService.save(pickupPointCategory);
            return ReturnBody.success("添加自提点分类成功!");
        } else {
            return ReturnBody.error("该自提点分类已存在!");
        }
    }

    /**
     * #0024 删除自提点分类
     * @param categoryId 分类id
     * @return 返回是否删除成功
     */
    @ApiOperation("删除自提点分类")
    @DeleteMapping("categories")
    public String deleteCategory(@NotNull(message = "未提交分类id") Integer categoryId) {
        SkdPickupPointCategory res = skdPickupPointCategoryService.getById(categoryId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该自提点分类不存在!");
        } else {
            skdPickupPointCategoryService.removeById(categoryId);
            return ReturnBody.success("删除成功!");
        }
    }

    /**
     * #0025 修改自提点分类名称
     * @param categoryId 分类id
     * @param name 修改名称
     * @return 返回是否修改成功
     */
    @ApiOperation("修改自提点分类名称")
    @PutMapping("categories")
    public String modifyCategory(@NotNull(message = "未提交分类id") Long categoryId, @NotBlank(message = "未提交修改的名称") String name) {
        SkdPickupPointCategory res = skdPickupPointCategoryService.getById(categoryId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该自提点分类不存在!");
        }

        SkdPickupPointCategory skdPickupPointCategory = new SkdPickupPointCategory();
        skdPickupPointCategory.setId(categoryId);
        skdPickupPointCategory.setName(name);
        skdPickupPointCategoryService.saveOrUpdate(skdPickupPointCategory);
        return ReturnBody.success("修改成功!");
    }

    /**
     * #0026 查询自提点分类列表
     * @return 返回分类列表
     */
    @ApiOperation("查询自提点分类列表")
    @GetMapping("categories")
    public String queryList() {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        List<Map<String, Object>> list = skdPickupPointCategoryService.queryListByUsId(usId);
        return ReturnBody.success(list);
    }

    /**
     * #0027 添加自提点
     * @return 返回添加成功信息
     */
    @ApiOperation("添加自提点")
    @PostMapping
    public String addPickupPoint(@Valid AddPickupPointReqVO reqVO) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }
        SkdPickupPoint skdPickupPoint = new SkdPickupPoint();
        skdPickupPoint.setUsId(usId).setName(reqVO.getName()).setLocation(reqVO.getLocation())
                .setLongitude(reqVO.getLongitude()).setLatitude(reqVO.getLatitude()).setAddress(reqVO.getAddress())
                .setContacts(reqVO.getContacts()).setPhoneNumber(reqVO.getPhoneNumber()).setCategoryId(reqVO.getCategoryId())
                .setImageUrl(reqVO.getImageUrl());
        skdPickupPointService.save(skdPickupPoint);
        return ReturnBody.success("添加成功!");
    }

    /**
     * #0028 作废自提点
     * @return 返回删除成功信息
     */
    @ApiOperation("作废自提点")
    @DeleteMapping
    public String deletePickupPoint(@NotNull(message = "未提交自提点id") Integer pickupPointId) {
        SkdPickupPoint res = skdPickupPointService.getById(pickupPointId);
        if (Objects.isNull(res)) {
            return ReturnBody.error("该自提点不存在!");
        }

        skdPickupPointService.removeById(pickupPointId);
        return ReturnBody.success("作废成功");
    }

    /**
     * #0029 修改自提点
     * @return 返回修改成功信息
     */
    @ApiOperation("修改自提点")
    @PutMapping
    public String modifyPickupPoint(@Valid ModifyPickupPointReqVO reqVO) {
        SkdPickupPoint res = skdPickupPointService.getById(reqVO.getId());
        if (Objects.isNull(res)) {
            return ReturnBody.error("该自提点不存在!");
        }
        SkdPickupPoint skdPickupPoint = new SkdPickupPoint();
        skdPickupPoint.setId(reqVO.getId()).setName(reqVO.getName()).setLocation(reqVO.getLocation())
                .setAddress(reqVO.getAddress()).setContacts(reqVO.getContacts()).setPhoneNumber(reqVO.getPhoneNumber())
                .setCategoryId(reqVO.getCategoryId()).setImageUrl(reqVO.getImageUrl());
        skdPickupPointService.saveOrUpdate(skdPickupPoint);
        return ReturnBody.success("修改成功!");
    }

    /**
     * #0030 查询自提点列表
     * @param queryName 查询名
     * @param categoryId 分类id
     * @return 返回自提点列表
     */
    @ApiOperation("查询自提点列表")
    @GetMapping
    public String queryPickupPoint(@RequestParam(name = "queryName", required = false) String queryName, @RequestParam(name = "categoryId", required = false) Integer categoryId) {
        Long usId;
        try {
            // 根据token获取用户id
            usId = tokenService.getUserIdFromToken();
        } catch (IllegalStateException e) {
            log.error(e.getMessage());
            return ReturnBody.error("token异常!");
        }

        // 当传递了分类ID且不为-1或0时，检查分类是否存在
        if (categoryId != null && categoryId != -1 && categoryId != 0) {
            boolean categoryExists = skdPickupPointCategoryService.count(new QueryWrapper<SkdPickupPointCategory>().eq("id", categoryId)) > 0;
            if (!categoryExists) {
                return ReturnBody.error("没有该自提点分类，请检查参数是否有效!");
            }
        }

        List<SkdPickupPoint> list = skdPickupPointService.queryPickupPoints(usId, queryName, categoryId);
        List<PickupPointResqVO> pickupPointResqVOList = list.stream().map(e -> {
            SkdPickupPointCategory skdPickupPointCategory = skdPickupPointCategoryService.getById(e.getCategoryId());
            String categoryName = skdPickupPointCategory != null ? skdPickupPointCategory.getName() : "未分类";
            return new PickupPointResqVO()
                    .setId(e.getId())
                    .setName(e.getName())
                    .setAddress(e.getLocation() + e.getAddress())
                    .setContacts(e.getContacts())
                    .setPhoneNumber(e.getPhoneNumber())
                    .setCategoryName(categoryName)
                    .setImageUrl(e.getImageUrl());
        }).collect(Collectors.toList());

        return ReturnBody.success(pickupPointResqVOList);
    }
}
